# get_bili_danmu.py (优化版)
from ratelimit import limits, sleep_and_retry
import requests
from datetime import datetime

class DanmuMonitor:
    def __init__(self, room_id):
        self.room_id = int(room_id)
        self.last_timeline = None  # 记录最新弹幕时间戳
        self.api_url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Origin': 'https://live.bilibili.com'
        }

    def dynamic_limit():
        if 9 <= datetime.now().hour <= 18:  # 高峰期
            print(f"[限速规则] 高峰期：5次/分钟")
            return limits(calls=5, period=60) #每分钟最多5次回复
        else:  # 低峰期
            print(f"[限速规则] 低峰期：3次/分钟")
            return limits(calls=3, period=60) #每分钟最多3次回复

    @sleep_and_retry
    @dynamic_limit()  # 限速
    def get_new_danmu(self):
        print(f"获取新弹幕...")
        params = {'roomid': self.room_id}
        try:
            resp = requests.get(self.api_url, headers=self.headers, params=params)
            resp_json = resp.json()
            # print(resp)
            # print(resp_json)
            # print(resp.url)
            latest_danmu = resp_json['data']['room'][-1]  # 获取最新一条弹幕
            if latest_danmu['timeline'] != self.last_timeline:
                self.last_timeline = latest_danmu['timeline']
                # 返回弹幕信息
                return {
                    'user': latest_danmu['nickname'],
                    'text': latest_danmu['text'],
                    'time': datetime.now().strftime("%H:%M:%S")
                }
        except Exception as e:
            print(f"弹幕获取异常: {e}")
            return None

